from celery import shared_task
from project import settings
from services.datamodel.vip.models import (mm_UserCards, UserCards)
from django.db import transaction
from apps.student.share import app_logger
import random


@shared_task(ignore_result=True)
def add_batch_generation_cards(card_batch_id, nums, role_id):
    # 显式的开启一个事务
    with transaction.atomic():
        # 创建事务保存点
        save_id = transaction.savepoint()
        # 暴力回滚
        try:
            inster_card = []
            for i in range(0, int(nums)):
                kwargs = {
                    'card_number': random.getrandbits(16*4),
                    'card_password': random.randrange(1, 999999, 6),
                    'card_batch_id': card_batch_id,
                    'status': 0,
                    'student_id': 1,  # 默认初始值为1,代表超级用户
                    'role_id': role_id
                }
                inster_card.append(UserCards(**kwargs))
            UserCards.objects.bulk_create(inster_card)
        except Exception as e:
            app_logger.error(e)
            transaction.savepoint_rollback(save_id)  # 回滚
            # 提交成功，显式的提交一次事务
        transaction.savepoint_commit(save_id)




